package com.pablosz.worm.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.content.Context;

public class File
{
	public static void write(Context ctx, String filename, String txt)
	{
		OutputStreamWriter os = null;
		try
		{
			os = new OutputStreamWriter(ctx.openFileOutput(filename, Activity.MODE_PRIVATE));
			os.write(txt);
			os.flush();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if( os!=null ) os.close();	
			}
			catch (Exception e2)
			{
				e2.printStackTrace();
			}
		}
	}

	public static String read(Context ctx, String filename)
	{
		InputStreamReader is = null;
		BufferedReader br = null;
		
		try
		{
			is = new InputStreamReader(ctx.openFileInput(filename));
			br = new BufferedReader(is);

			int c;
			StringBuffer buff = new StringBuffer();
			while( (c=br.read()) >=0 )
			{
				buff.append((char)c);
			}
			return buff.toString();
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if( br!=null ) br.close();
				if( is!=null ) is.close();
			}
			catch (Exception e2)
			{
				e2.printStackTrace();
			}
		}
		
		return null;
	}

	public static boolean exists(Context ctx, String filename)
	{
		String filelist[] = ctx.fileList();
		for(String s:filelist)
		{
			if( s.equals(filename) )
			{
				return true;
			}
		}
		
		return false;
	}
}
